﻿using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using S.EliminationOrDath.Domain;
using S.EliminationOrDath.Domain.Models;
using S.EliminationOrDath.Infrastructure.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;

namespace S.EliminationOrDath.Infrastructure.Impl
{
    /// <summary>
    /// 羊只死亡——仓储
    /// </summary>
    public class SheepDeathRepository : BaseRepository<DeathModel>, ISheepDeathRepository
    {
        private readonly EliminationDbContext _db;
        //构造函数引用上下文
        public SheepDeathRepository(EliminationDbContext db) : base(db)
        {
            _db = db;
        }
        /// <summary>
        /// 根据ids进行批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> BacthDelete(List<int> ids)
        {
            var result = await _db.Set<DeathModel>().Where(a => ids.Contains(a.DeathId)).ToListAsync();
            _db.Set<DeathModel>().RemoveRange(result);
            return await _db.SaveChangesAsync() > 0;
        }
        /// <summary>
        /// 查询批量选择的DeathIds
        /// </summary>
        /// <param name="DeathIds"></param>
        /// <returns></returns>
        public async Task<List<DeathModel>> GetDeathsids(string? DeathIds)
        {
            try
            {
                if (string.IsNullOrEmpty(DeathIds))
                {
                    return null;
                }

                // 将字符串转换为整数数组
                var deathIdArray = DeathIds.Split(',').Select(id => int.Parse(id)).ToArray();

                // 构建参数化查询
                var parameters = new List<SqlParameter>();
                var parameterNames = new List<string>();
                for (int i = 0; i < deathIdArray.Length; i++)
                {
                    var paramName = $"@id{i}";
                    parameterNames.Add(paramName);
                    parameters.Add(new SqlParameter(paramName, deathIdArray[i]));
                }

                // 构建 SQL 查询语句
                var sql = $"SELECT * FROM DeathModel WHERE DeathId IN ({string.Join(',', parameterNames)});";

                // 执行查询并返回结果
                var list = await _db.DeathModel
                    .FromSqlRaw(sql, parameters.ToArray())
                    .ToListAsync();

                return list;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 审批方法
        /// </summary>
        /// <param name="DeathIds"></param>
        /// <returns></returns>
        public async Task<bool> UpdAuditor(string? DeathIds, string? uname)
        {
            try
            {
                if (string.IsNullOrEmpty(DeathIds) || string.IsNullOrEmpty(uname))
                {
                    return false; // 请检查参数的有效性
                }

                var deathIdsArray = DeathIds.Split(',').Select(id => int.Parse(id)).ToArray(); // 将字符串转换为整数数组
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                // 使用参数化查询
                var sql = new StringBuilder("UPDATE DeathModel SET Auditor = @uname, AuditorTime = @time WHERE DeathId IN (");
                var parameters = new List<SqlParameter>
                {
                    new SqlParameter("@uname", uname),
                    new SqlParameter("@time", time)
                };

                for (int i = 0; i < deathIdsArray.Length; i++)
                {
                    sql.Append("@id" + i);
                    if (i < deathIdsArray.Length - 1)
                    {
                        sql.Append(", ");
                    }
                    parameters.Add(new SqlParameter("@id" + i, deathIdsArray[i]));
                }
                sql.Append(");");

                var result = await _db.Database.ExecuteSqlRawAsync(sql.ToString(), parameters.ToArray());
                return result > 0;
            }
            catch (Exception ex)
            {
                //处理异常
                Console.WriteLine("错误异常：" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 取消审批方法
        /// </summary>
        /// <param name="DeathIds"></param>
        /// <returns></returns>
        public async Task<bool> UpdAuditorTow(string? DeathIds)
        {
            try
            {
                if (string.IsNullOrEmpty(DeathIds))
                {
                    return false;
                }
                //将字符串转换为整数数组
                var deathIdsArray=DeathIds.Split(',').Select(id=>int.Parse(id)).ToArray();

                var sql = new StringBuilder("UPDATE DeathModel SET Auditor = 1, AuditorTime = '' WHERE DeathId IN (");
                var parameters =new List<SqlParameter>();
                for (int i = 0; i < deathIdsArray.Length; i++)
                {
                    sql.Append("@id" + i);
                    if (i < deathIdsArray.Length - 1)
                    {
                        sql.Append(", ");
                    }
                    parameters.Add(new SqlParameter("@id"+i, deathIdsArray[i]));
                }
                sql.Append(");");
                var res=await _db.Database.ExecuteSqlRawAsync(sql.ToString(),parameters.ToArray());
                return res > 0;
            }
            catch (Exception ex)
            {
                //处理异常
                Console.WriteLine("错误异常：" + ex.Message);
                throw;
            }
        }
    }
}
